const { JSDOM } = require('jsdom')

const getCategory = ({ res, response }) => {
  res.setHeader('Content-Type', 'application/json')
  try {
    const dom = new JSDOM(response)
    const document = dom.window.document
    const categoryList = []

    const domList = [...document.querySelector('.from1').querySelectorAll('li')]

    domList.forEach(li => {
      const href = li
        .querySelector('.cbuy')
        .querySelectorAll('a')[0]
        .href.split('/')
      const code = href[href.length - 1]
      const pic = li.querySelector('.fl').querySelector('img').src

      const goodsName = li.querySelector('.title').querySelector('a').innerHTML
      let price =
        li.querySelector('.csale_price').querySelector('em') ||
        li.querySelector('.cprice')
      price = price.innerHTML.replace(/\s+/g, '').replace(/售价/, '')

      categoryList.push({
        code,
        pic,
        goodsName,
        price
      })
    })

    return JSON.stringify({
      data: categoryList,
      success: true
    })
  } catch (error) {
    return JSON.stringify({
      success: false
    })
  }
}

module.exports = {
  getCategory
}
